package com.zksw.redis;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;

public class RedisDao {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    public void set(final String key, final String value) {
        redisTemplate.execute(new RedisCallback<Object>() {
            @Override
            public Object doInRedis(RedisConnection redisConnection) throws DataAccessException {
                redisConnection.set(redisTemplate.getStringSerializer().serialize(key),
                        redisTemplate.getStringSerializer().serialize(value));
                return null;
            }
        });
    }

    public void setEx(final String key, final Long seconds, final String value) {
        redisTemplate.execute(new RedisCallback<Object>() {
            @Override
            public Object doInRedis(RedisConnection redisConnection) throws DataAccessException {
                redisConnection.setEx(redisTemplate.getStringSerializer().serialize(key), seconds,
                        redisTemplate.getStringSerializer().serialize(value));
                return null;
            }
        });
    }

    public String get(final String key) {
        return redisTemplate.execute(new RedisCallback<String>() {
            @Override
            public String doInRedis(RedisConnection redisConnection) throws DataAccessException {
                byte[] k = redisTemplate.getStringSerializer().serialize(key);
                if (redisConnection.exists(k)) {
                    return redisTemplate.getStringSerializer().deserialize(redisConnection.get(k));
                }
                return null;
            }
        });
    }

    public void delete(final String key) {
        redisTemplate.execute(new RedisCallback<Object>() {
            @Override
            public Object doInRedis(RedisConnection redisConnection) throws DataAccessException {
                byte[] k = redisTemplate.getStringSerializer().serialize(key);
                if (redisConnection.exists(k)) {
                    redisConnection.del(k);
                }
                return null;
            }
        });
    }

    public void setMap(String key, Map<Object, Object> valueMap) {
    	redisTemplate.opsForHash().putAll(key, valueMap);
    }
    
    public Map<Object, Object> getMap(String key) {
    	return redisTemplate.opsForHash().entries(key);
    }

}
